package com.example.demo.service.impl;

import com.example.demo.concurrent.MyThreadPool;
import com.example.demo.domain.MyUser;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.MyService;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： 76875
 * @date： 2022/1/6 星期四 19:49
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
@Service
public class MyServiceImpl implements MyService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public String batchInsertUser() {
        long l = 0;
        try {
            ThreadPoolExecutor threadPoolExecutor = MyThreadPool.getThreadPoolExecutor();
            // 插入1000万条数据

            // 尝试构造一万条数据
            int sumCount = 1000;
            Date start = new Date();
            CountDownLatch countDownLatch = new CountDownLatch(sumCount);
            for (int i = 0; i < sumCount; i++) {
                try {
                    threadPoolExecutor.execute(()->{
                        List<MyUser> myUsers = initBatchUser(10000);
                        userRepository.saveAllAndFlush(myUsers);
                    });
                } finally {
                    countDownLatch.countDown();
                }
            }
            countDownLatch.await();
            Date end = new Date();
            l = end.getTime() - start.getTime();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "耗费时间"+l;
    }

    public List<MyUser> initBatchUser(int initNum){
        LinkedList<MyUser> myUsers = new LinkedList<>();
        String randomStr = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < initNum; i++) {
            myUsers.add(createRandomUser(randomStr+i));
        }
        return myUsers;
    }

    private MyUser createRandomUser(String base){
        MyUser myUser = new MyUser();
        String s = base + RandomUtils.nextInt();
        myUser.setUserName(s);
        myUser.setRealName(s);
        myUser.setSex("man");
        myUser.setAge(10);
        myUser.setPhone("13015470301");
        myUser.setAddress("陕西省西安市");
        myUser.setEnableFlag(1);
        return myUser;
    }
}
